/*
 *	$Id: parser.cpp 165 2009-06-20 09:48:01Z wabsie $
 */

#include "parser.h" // Hvis andre #include's i denne fil end denne, så slet dem

parser::parser(vizobj *_viz)
{
	this->viz = _viz;
}

vector<string> parser::split(const string& str, char delim)
{
	vector<string> tokens;
	stringstream ss(str);
	string token;

	while (getline(ss, token, delim))
		tokens.push_back(token);

	return tokens;
}

string parser::trim(const string& arg, char remove)
{
	string res;
	for (int i = 0; i < arg.size(); i++) {
		if (arg[i] == remove) continue;
		res += arg[i];
	}
	return res;
}

skalar parser::string2skalar(const string& str)
{
	skalar val;

	skalar mantissa = 0;
	skalar exponent = 0;
	vector<string> tok = split(str, 'E');

	switch (tok.size()) {
		case 2:
			exponent = atof(tok[1].c_str());
		case 1:
			mantissa = atof(tok[0].c_str());
	}

	val = mantissa * pow(10, exponent);

	return val;
}

vektor<3> parser::string2vektor(const string& str)
{
	vektor<3> v;

	vector<string> components = split(str, ';');
	for (int i = 0; i < components.size(); i++) {
		v.data[i][0] = string2skalar(components[i]);
	}
	
	return v;
}

void parser::createVIZ(string emtype, vector<string>& args)
{
	emobj::type typ = emobj::unknown;
	skalar styrke = 0;
	vektor<3> offset;
	vektor<3> ret;

	for (int i = 0; i < args.size(); i++) {
		args[i] = trim(args[i], ' ');
		args[i] = trim(args[i], ']');
		args[i] = trim(args[i], '[');
	}

	for (int i = 0; i < 3; i++) {
		if (string(emobj::strType[i]) == emtype) {
			typ = (emobj::type)i;
			break;
		}
	}

	switch (args.size()) {
		case 3:
			ret = string2vektor(args[2]);
		case 2:
			offset = string2vektor(args[1]);
		case 1:
			styrke = string2skalar(args[0]);
			break;
	}

	this->viz->vem.addObj(typ, styrke, offset, ret);

	return;
}

void parser::text2VIZ(vector<string>& linjer)
{
	for (int i = 0; i < linjer.size(); i++)
	{
		string emtype;
		vector<string> args;

		vector<string> tokens;
		string linje = linjer[i];

		if (linje.empty())	continue;

		// Fjern kommentarer
		tokens = split(linje, '#');
		if (tokens.empty()) continue;
		linje = tokens[0];
		if (linje.empty())	continue;

		// Find type
		tokens = split(linje, '(');
		if (tokens.size() != 2) continue;
		emtype = tokens[0];
		tokens = split(tokens[1], ')');

		args = split(tokens[0], ',');

		createVIZ(emtype, args);
	}

	return;
}

